package 查找算法;

/**
 * @author kakayubei
 * @description
 * @date 2021/10/9 23:18
 */
public class BinarySearch {
    /**
     * 二分查找
     *
     * @param array
     * @param key
     * @return
     */
    public static int binarySearch(int[] array, int key) {
        int low = 0;
        int high = array.length - 1;
        while (low <= high) {
            int mid = low + ((high - low) >> 1);
            if (array[mid] == key) {
                return mid;
            }
            if (array[mid] > key) {
                high = mid - 1;
            } else {
                low = mid + 1;
            }
        }
        return -1;
    }

    /**
     * 递归二分查找
     *
     */
    public static int binarySearch2(int[] array, int key) {
        int low = 0;
        int high = array.length - 1;
        return search(array, low, high, key);
    }

    public static int search(int[] array, int low, int high, int key) {
        if (low > high) {
            return -1;
        }
        int mid = low + ((high - low) >> 1);
        if (array[mid] == key) {
            return mid;
        }
        if (array[mid] > key) {
            return search(array, low, mid - 1, key);
        } else {
            return search(array, mid + 1, high, key);
        }
    }

    public static void main(String[] args) {
        int i = binarySearch(new int[] { 1, 2, 3, 4, 5 }, 3);
        System.out.println(i);
    }
}
